package com.ygxsk.carhome.ui.signature;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.response.EvaluteCurrentItemBean;
import com.ygxsk.carhome.response.LeadListItemBean;
import com.ygxsk.carhome.response.RepairManageItemBean;
import com.ygxsk.carhome.response.RunManGroupHeadOrTeamCheck;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.rxbus.RxBusRunManGroupHeadOrTeamCheck;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.SignatureGroupHeadManMemberAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-13  15:54
 * @Description:人员管理页面
 */
public class SignatureManagerGroupActivity extends ErrorActivity implements ErrorParentExtraSingle {

    @BindView(R.id.refreshlayoutingroupheadman_signature)
    SmartRefreshLayout refreshLayoutInGroupHeadMan_signature;

    @BindView(R.id.recyclerviewingroupheadman_signature)
    RecyclerView recyclerViewInGroupHeadMan_signature;

    private ArrayList<RunManGroupHeadOrTeamCheck> mDatasResources = new ArrayList<>();

    //合同档案的适配器，和潜客列表的做区分开
    private SignatureGroupHeadManMemberAdapter signatureGroupHeadManMemberAdapter;

    //从哪里过来
    private int extra_jumpfrom_where;
    //携带从列表过来的,直接携带过去,主要是为了获取 人员列表的类型
    private LeadListItemBean extra_lead_list_item_bean;

    //添加 是车辆评估的 这条数据携带
    private EvaluteCurrentItemBean extra_evalute_current_item_bean;

    //预约维保 获取销售人员列表--售后人员列表
    private RepairManageItemBean extra_repair_manage_item_bean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        processExtraData();

        initloading();

        initViews();

        // TODO: 2023-07-14 14:47 真实开发放开


        gainDatas();


    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_signatrue_manager_group;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

//      toolbarHelper.setTitle(getString(R.string.choose_sell_person));
        toolbarHelper.setTitle(getString(R.string.choose_sell_person_other));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());

        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        toolbarHelper.setLayoutRight(false, 0, "", null);

    }

    @Override
    protected void onClickNodata(View v) {
        gainDatas();
    }

    @Override
    protected void initViews() {

        signatureGroupHeadManMemberAdapter = new SignatureGroupHeadManMemberAdapter(R.layout.signature_group_member_adapter, mDatasResources);
        recyclerViewInGroupHeadMan_signature.setLayoutManager(new MyLinearLayoutManager(this));
        recyclerViewInGroupHeadMan_signature.clearAnimation();

        recyclerViewInGroupHeadMan_signature.setAdapter(signatureGroupHeadManMemberAdapter);
        signatureGroupHeadManMemberAdapter.notifyDataSetChanged();

        signatureGroupHeadManMemberAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                RunManGroupHeadOrTeamCheck runManGroupHeadOrTeamCheck = (RunManGroupHeadOrTeamCheck) adapter.getItem(position);

                if (runManGroupHeadOrTeamCheck != null) {
                    //2023-11-6 15:50:34改为拷贝电话号码
                    CommUtils.methodCopyClip(runManGroupHeadOrTeamCheck.getPhone(), true);
                    //clickButton_toCallPhone(SignatureManagerGroupActivity.this, runManGroupHeadOrTeamCheck.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_7.getIndex());
                }

                return true;
            }
        });

//        signatureGroupHeadManMemberAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
//
//
//
//            }
//        });

        signatureGroupHeadManMemberAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                RunManGroupHeadOrTeamCheck runManGroupHeadOrTeamCheck = (RunManGroupHeadOrTeamCheck) adapter.getItem(position);

                if (runManGroupHeadOrTeamCheck != null) {

                    //2023年10月27日11:21:48 新修改逻辑
                    //如果是从【新车销售的 法大大电子签章 签约合同页过来的】
                    method_gainAssignPerson_upLoad_forSignatureAddSubmit(runManGroupHeadOrTeamCheck);

                } else {

                    //拦截
//                    if (ObjectUtils.isEmpty(rxBusRunManGroupHeadMan.getRunManGroupHeadOrTeamCheck())) {
//                        ToastUtils.showShort(R.string.choose_person);
//                        return;
//                    }

                    //选中的人员值为空
                    ToastUtils.showShort(getResources().getString(R.string.choose_person_is_null));
                }

            }
        });


        //暂时设置 仅仅只有下拉刷新，没有加载更多；
        refreshLayoutInGroupHeadMan_signature.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        if (mDatasResources != null && !mDatasResources.isEmpty()) {
                            mDatasResources.clear();
                        }

                        if (signatureGroupHeadManMemberAdapter != null) {
                            signatureGroupHeadManMemberAdapter.notifyDataSetChanged();
                        }

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }
        });

    }

    @Override
    protected void gainDatas() {

        if (mDatasResources != null && !mDatasResources.isEmpty()) {
            mDatasResources.clear();
        }

        if (NetworkUtils.isConnected()) {

            getServerDatas_signatureAddSubmit();

        } else {
            netWorkError();
        }

    }

    //选中经理人的提交给预约申请页面
    private void method_gainAssignPerson_upLoad_forSignatureAddSubmit(RunManGroupHeadOrTeamCheck _runManGroupHeadOrTeamCheck) {

        //这里是员工的二维码信息
        RxBusRunManGroupHeadOrTeamCheck rxBusRunManGroupHeadOrTeamCheck = new RxBusRunManGroupHeadOrTeamCheck(ExtraValue.RXBUS_RUNMANGROUP_TEAMMAN);
        rxBusRunManGroupHeadOrTeamCheck.setRunManGroupHeadOrTeamCheck(_runManGroupHeadOrTeamCheck);
        RxBus.getInstance().post(rxBusRunManGroupHeadOrTeamCheck);

        //关闭该页面内容
        methodBack();

    }


    //获取人员列表信息
    private void getServerDatas() {
//        {
//                "shopInfoId": 1495,
//                "saleType": 1
//        }

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());

        map.put(Parameterkey.saleType, extra_lead_list_item_bean.getLatentType());

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETSALEINFOLIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getSaleInfoList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getSaleInfoList(RequestBody.create(JSON.toJSONString(map,//
                                SerializerFeature.PrettyFormat, //
                                SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(SignatureManagerGroupActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        // TODO: 2023-08-10 15:51 空数据处理

                    }
                })).subscribe(new Consumer<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void accept(ArrayList<RunManGroupHeadOrTeamCheck> runManGroupHeadOrTeamCheckArrayList) throws Throwable {

                        methodHandlerSuccess(runManGroupHeadOrTeamCheckArrayList);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });


    }

    //获取合同签约的 销售人员，这里是全部的员工？还是仅仅是销售人员
    private void getServerDatas_signatureAddSubmit() {

        //        {
//                "shopInfoId": 1495,
//                "saleType": 1
//        }

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
//      map.put(Parameterkey.vehicleType, 1);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETCUSTOMERLISTBYSHOP_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getCustomerListByShop_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
//                .getMyManagers(RequestBody.create(JSON.toJSONString(map,//
//                                SerializerFeature.PrettyFormat, //
//                                SerializerFeature.WriteMapNullValue), //
//                        MediaType.parse(ApiService.HEADER_JSON)))//
                .getMyManagers()
                .compose(SignatureManagerGroupActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }

                    }
                })).subscribe(new Consumer<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void accept(ArrayList<RunManGroupHeadOrTeamCheck> runManGroupHeadOrTeamCheckArrayList) throws Throwable {

                        //填充列表
                        methodHandlerSuccess(runManGroupHeadOrTeamCheckArrayList);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        if (apiException != null) {
                            ToastUtils.showShort(apiException.getDisplayMessage());
                        }

                    }
                });


    }

    //获取预约维保的获取销售人员列表接口
    private void getServerDatas_bookingRepair() {

        //        {
//                "shopInfoId": 1495,
//                "saleType": 1
//        }

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.saleType, "3");

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETSALEINFOLIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getSaleInfoList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getSaleInfoList(RequestBody.create(JSON.toJSONString(map,//
                                SerializerFeature.PrettyFormat, //
                                SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(SignatureManagerGroupActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void accept(ArrayList<RunManGroupHeadOrTeamCheck> runManGroupHeadOrTeamCheckArrayList) throws Throwable {

                        methodHandlerSuccess(runManGroupHeadOrTeamCheckArrayList);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });


    }

    //车辆评估的获取销售人员列表，这里主要是获取 二手车销售："saleType": 1 //类别：1新车销售；2二手车销售；3售后

    private void getServerDatas_evaluate() {
//        {
//                "shopInfoId": 1495,
//                "saleType": 1
//        }

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.saleType, "2");

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETSALEINFOLIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getSaleInfoList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getSaleInfoList(RequestBody.create(JSON.toJSONString(map,//
                                SerializerFeature.PrettyFormat, //
                                SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(SignatureManagerGroupActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void accept(ArrayList<RunManGroupHeadOrTeamCheck> runManGroupHeadOrTeamCheckArrayList) throws Throwable {

                        methodHandlerSuccess(runManGroupHeadOrTeamCheckArrayList);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });


    }

    private void methodHandlerSuccess(ArrayList<RunManGroupHeadOrTeamCheck> _runManGroupHeadOrTeamCheckArrayList) {

        if (_runManGroupHeadOrTeamCheckArrayList != null && !_runManGroupHeadOrTeamCheckArrayList.isEmpty()) {

            if (mDatasResources != null) {
                mDatasResources.addAll(_runManGroupHeadOrTeamCheckArrayList);
            }
            //先判断外侧，是不是为空，为空就是新进入添加，不是空，就是有历史记录的

        } else {
            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
        }

        if (signatureGroupHeadManMemberAdapter != null) {
            signatureGroupHeadManMemberAdapter.notifyDataSetChanged();
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

//        if (!TextUtils.isEmpty(extra_runmangroup_headman_teamleaderid)) {
//            extra_runmangroup_headman_teamleaderid = "";
//        }

        if (mDatasResources != null && !mDatasResources.isEmpty()) {

            mDatasResources.clear();

            if (signatureGroupHeadManMemberAdapter != null) {
                signatureGroupHeadManMemberAdapter.notifyDataSetChanged();
                signatureGroupHeadManMemberAdapter = null;
            }

            mDatasResources = null;
        }

    }

    @Override
    protected void methodBack() {
        if (ActivityUtils.isActivityAlive(this)) {
            ActivityUtils.finishActivity(this);
        }
    }


    @Override
    public void processExtraData() {

        //页面跳转传值bundle
        Bundle bundle = this.getIntent().getExtras();

        //use the data received here
        if (bundle != null) {

            //判断父亲入口是从哪里 进来的，是【新增小组】还是【修改小组】，修改小组不用传递groupid
            extra_jumpfrom_where = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);

            //携带潜客的部分信息，用来确认  //类别：1新车销售；2二手车销售；3售后
            extra_lead_list_item_bean = bundle.getParcelable(ExtraKey.EXTRA_LEAD_LIST_ITEM_BEAN);

            extra_evalute_current_item_bean = bundle.getParcelable(ExtraKey.EXTRA_EVALUTE_CURRENT_ITEM_BEAN);

            extra_repair_manage_item_bean = bundle.getParcelable(ExtraKey.EXTRA_REPAIR_MANAGE_ITEM_BEAN);

            //如果是修改小组，那么传递小组的id过来；
//            groupId_upLoad = bundle.getString(ExtraKey.EXTRA_RUNMANGROUP_GROUP_ID);//EXTRA_RUNMANGROUP_GROUP_ID

//            LogUtils.d(ConstantSign.LOGCAT_NOMAL+"extra_jumpfrom_where-->"+extra_jumpfrom_where+"--groupId_upLoad-->"+groupId_upLoad);

            //处理携带的所属县域id,用来查询这个县域的小组长，
//            extra_runmangroup_countydeptid_upload = bundle.getString(ExtraKey.EXTRA_RUNMANGROUP_COUNTYDEPTID_UPLOAD);

            //处理携带data
//            extra_runmangroup_headman_teamleaderid = bundle.getString(ExtraKey.EXTRA_RUNMANGROUP_HEADMAN_TEAMLEADERID);

        }


    }
}